#include "fontmap.hpp"

#include <assert.h>
#include <iostream>

inline int next_p2 (int a )
{
  int rval=1;
  // rval<<=1 ЩРН КСВЬЕ ВЕЛ rval*=2;
  while(rval<a) rval<<=1;
  return rval;
}


FontMap::FontMap()
{
  FT_Error error = FT_Init_FreeType( &library );
  assert(!error);
}

FontMap::~FontMap()
{

}

bool FontMap::Prepare(std::string fontname, 
		      uint fontsize)
{

  FT_Error error = FT_New_Face( library,
				fontname.c_str(),
				0,
				&face );
  assert(error != FT_Err_Unknown_File_Format);
  assert(!error);
  error = FT_Set_Char_Size(face,   
			   0,
			   40*64,
			   fontsize,
			   fontsize );
  
  FT_GlyphSlot  slot = face->glyph;  // a small shortcut 
  int           pen_x, pen_y;
  pen_x = 300;
  pen_y = 200;
    
  for (unsigned char n = 0; n < 255; n++ )
    {
      std::cout<<"Generate glyf"<<(int)n<<std::endl;
      FT_UInt  glyph_index = FT_Get_Char_Index( face, n );
      error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT );
      if ( error )
	{
	  continue;
	}
      
      error = FT_Render_Glyph( face->glyph, FT_RENDER_MODE_NORMAL );
      if ( error )
	continue;

      FT_Bitmap& bitmap=slot->bitmap;
      
      int width = next_p2( bitmap.width );
      int height = next_p2( bitmap.rows );
      
      charInfo_[n].dataLength_ =  2 * bitmap.width * bitmap.rows;
      charInfo_[n].data_ = new unsigned char[2 * bitmap.width * bitmap.rows];
      
      for(int j=0; j <bitmap.rows;j++) {
	for(int i=0; i < bitmap.width; i++){
	  charInfo_[n].data_[i+ (bitmap.width * j)] =
	   bitmap.buffer[i + bitmap.width*j];
	}
      }
      charInfo_[n].width = bitmap.width;
      charInfo_[n].height = bitmap.rows;
      charInfo_[n].top = slot->bitmap_top;
      charInfo_[n].twidth = static_cast<float>(bitmap.width) / static_cast<float>(width);
      charInfo_[n].theight = static_cast<float>(bitmap.rows) / static_cast<float>(height);

      
    }	
  
  return true;
  
}

FontChar_P FontMap::getChar(unsigned char ch)
{
  return &charInfo_[ch];
}
